package com.butnet.sqltools.web;

import java.io.File;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.butnet.sqltools.connection.Config;
import com.butnet.sqltools.connection.DBTools;
import com.butnet.sqltools.connection.DBTools.ExecOver;

/**
 * Servlet implementation class Action
 */
public class Action extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static DBTools dbTools = new DBTools();
	public static int getMaxHistoryCount() {
		return dbTools.getMaxHistoryCount();
	}
	public void setMaxHistoryCount(int maxHistoryCount) {
		dbTools.setMaxHistoryCount(maxHistoryCount);
	}
	
	@Override
	public void init(ServletConfig config) throws ServletException {
		String value = config.getInitParameter("maxHistoryCount");
		try{
			setMaxHistoryCount(Integer.parseInt(value));
		}catch(Exception e){
			e.printStackTrace(System.err);
		}
	}
	public static DBTools getDbTools() {
		return dbTools;
	}

	/**
	 * Default constructor.
	 */
	public Action() {
	}

	private void process(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException {
		res.setCharacterEncoding("GBK");
		res.setContentType("text/html; charset=GBK");
		req.setCharacterEncoding("UTF-8");
		String method = req.getParameter("method");
		String name = req.getParameter("name");
		String sql = req.getParameter("sql");
		if (method != null) {
			if (method.equalsIgnoreCase("search")) {
				searchConfig(req, res);
			} else if (method.equalsIgnoreCase("bulid")) {
				if (name == null || name.trim().length() == 0) {
					res.getWriter().print("缺少参数name");
					return;
				}
				if (getDbTools().get(name) != null) {
					if (sql != null && sql.trim().length() > 0) {
						ExecOver over = null;
						try {
							over = getDbTools().executeQuery(name, sql);
							req.setAttribute("over", over);
							req.getRequestDispatcher("over.jsp").forward(req, res);
						} catch (Exception e) {
							e.printStackTrace(res.getWriter());
							return;
						}
					} else {
						try {
							if(getDbTools().get(name).isClosed()){
								getDbTools().build(getDbTools().getConfig(name));
							}
						} catch (SQLException e) {
							res.getWriter().println("连接失败:<br/>");
							e.printStackTrace(res.getWriter());
							return;
						}
						res.getWriter().println("已创建连接");
					}
				} else {
					File dir = new File(req.getSession().getServletContext().getRealPath("/WEB-INF/config/"));
					File f = new File(dir, name + ".conf");
					if (!f.exists()) {
						res.getWriter().print("配置文件: " + name + " 不存在");
						return;
					}

					Config conf = Config.readConfig(f.getPath());
					conf.setName(name);
					System.out.println(conf.getName() + "-------------------");
					if (getDbTools().build(conf) == null) {
						getDbTools().getLastError().printStackTrace(res.getWriter());
					} else {
						if (sql != null && sql.trim().length() > 0) {
							ExecOver over = null;
							try {
								over = getDbTools().executeQuery(name, sql);
								req.setAttribute("over", over);
								req.getRequestDispatcher("over.jsp").forward(req, res);
							} catch (SQLException e) {
								e.printStackTrace(res.getWriter());
							}
						}else{
							res.getWriter().println("已创建连接");
						}
					}
				}
			}else if(method.equalsIgnoreCase("close")){
				if(name==null||name.trim().length()==0){
					res.getWriter().println("缺少参数");
					return;
				}else{
					if(dbTools.close(name)){
						res.getWriter().println("关闭成功");
					}else{
						res.getWriter().println("关闭失败");
					}
				}
			}else if(method.equalsIgnoreCase("config")){
				String config = req.getParameter("config");
				if(!name.startsWith(".conf"))name+=".conf";
				String filePath = req.getSession().getServletContext().getRealPath("/WEB-INF/config/"+name);
				FileOutputStream out = new FileOutputStream(filePath);
				out.write(config.getBytes());
				out.close();
				res.getWriter().print("保存成功");
			}else if(method.equalsIgnoreCase("delete")){
				String config = req.getParameter("config");
				if(!name.startsWith(".conf"))name+=".conf";
				String filePath = req.getSession().getServletContext().getRealPath("/WEB-INF/config/"+name);
				File file = new File(filePath);
				if(file.exists())
					if(file.delete())
						res.getWriter().println("删除成功");
					else
						res.getWriter().println("删除失败");
				else
					res.getWriter().println("配置 "+name+" 文件不存在");
			}
		} else {
			res.getWriter().print("错误的参数");
		}
	}

	private void searchConfig(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
		File dir = new File(req.getSession().getServletContext().getRealPath("/WEB-INF/config/"));
		if (!dir.exists()) {
			req.getRequestDispatcher("/list.jsp").forward(req, res);
			return;
		}
		File[] confs = dir.listFiles(new FilenameFilter() {
			@Override
			public boolean accept(File dir, String name) {
				if (name.toLowerCase().endsWith(".conf"))
					return true;
				return false;
			}
		});
		List<String> names = new LinkedList<String>();
		for (File f : confs) {
			String name = f.getName();
			int index = name.lastIndexOf('.');
			if (index != -1)
				name = name.substring(0, index);
			names.add(name);
		}
		req.setAttribute("names", names);
		req.getRequestDispatcher("/list.jsp").forward(req, res);
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		process(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
			IOException {
		process(request, response);
	}
}
